package com.ruoyi.lock.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.lock.domain.ADevice;
import com.ruoyi.lock.service.IADeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 设备管理Controller
 * 
 * @author arvin
 * @date 2025-03-02
 */
@RestController
@RequestMapping("/lock/device")
public class ADeviceController extends BaseController
{
    @Autowired
    private IADeviceService aDeviceService;

    /**
     * 查询设备管理列表
     */
    @PreAuthorize("@ss.hasPermi('lock:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(ADevice aDevice)
    {
        startPage();
        List<ADevice> list = aDeviceService.selectADeviceList(aDevice);
        return getDataTable(list);
    }

    /**
     * 导出设备管理列表
     */
    @PreAuthorize("@ss.hasPermi('lock:device:export')")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ADevice aDevice)
    {
        List<ADevice> list = aDeviceService.selectADeviceList(aDevice);
        ExcelUtil<ADevice> util = new ExcelUtil<ADevice>(ADevice.class);
        util.exportExcel(response, list, "设备管理数据");
    }

    /**
     * 获取设备管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('lock:device:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(aDeviceService.selectADeviceById(id));
    }

    /**
     * 新增设备管理
     */
    @PreAuthorize("@ss.hasPermi('lock:device:add')")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ADevice aDevice)
    {
        // 检查MAC地址是否已被使用
        ADevice existDevice = new ADevice();
        existDevice.setMac(aDevice.getMac());
        List<ADevice> devices = aDeviceService.selectADeviceList(existDevice);
        if (devices != null && !devices.isEmpty()) {
            return error("设备MAC地址 [" + aDevice.getMac() + "] 已被绑定，请先解绑后再添加");
        }
        
        return toAjax(aDeviceService.insertADevice(aDevice));
    }

    /**
     * 修改设备管理
     */
    @PreAuthorize("@ss.hasPermi('lock:device:edit')")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ADevice aDevice)
    {
        // 检查MAC地址是否已被其他设备使用
        ADevice existDevice = new ADevice();
        existDevice.setMac(aDevice.getMac());
        List<ADevice> devices = aDeviceService.selectADeviceList(existDevice);
        
        // 如果找到了MAC相同的设备，且不是当前修改的设备
        if (devices != null && !devices.isEmpty()) {
            boolean isMacUsedByOther = devices.stream()
                .anyMatch(device -> !device.getId().equals(aDevice.getId()));
            
            if (isMacUsedByOther) {
                return error("设备MAC地址 [" + aDevice.getMac() + "] 已被其他设备绑定，请先解绑后再修改");
            }
        }
        
        return toAjax(aDeviceService.updateADevice(aDevice));
    }
    @PreAuthorize("@ss.hasPermi('lock:device:edit')")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping("update")
    public AjaxResult update(@RequestBody ADevice aDevice)
    {

        return toAjax(aDeviceService.updateADeviceByMac(aDevice));
    }
    /**
     * 删除设备管理
     */
    @PreAuthorize("@ss.hasPermi('lock:device:remove')")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(aDeviceService.deleteADeviceByIds(ids));
    }
    
    /**
     * 根据房间ID查询设备列表
     */
    @GetMapping("/listByHomeId/{homeId}")
    public AjaxResult listByHomeId(@PathVariable("homeId") Long homeId)
    {
        return success(aDeviceService.selectADeviceListByHomeId(homeId));
    }

    /**
     * 查询未激活锁数量
     */
    @GetMapping("/unactivated/count")
    public AjaxResult getUnactivatedLockCount(ADevice device)
    {
        return success(aDeviceService.selectUnactivatedLockCount(device));
    }

    /**
     * 查询信号弱的锁数量
     */
    @GetMapping("/weaksignal/count")
    public AjaxResult getWeakSignalLockCount(ADevice device)
    {
        return success(aDeviceService.selectWeakSignalLockCount(device));
    }

    /**
     * 查询通信时间异常的锁数量
     */
    @GetMapping("/abnormaldate/count")
    public AjaxResult getAbnormalDateLockCount(ADevice device)
    {
        return success(aDeviceService.selectAbnormalDateLockCount(device));
    }

    /**
     * 查询管理员密码异常的锁数量
     */
    @GetMapping("/abnormaladmin/count")
    public AjaxResult getAbnormalAdminPwdCount(ADevice device)
    {
        return success(aDeviceService.selectAbnormalAdminPwdCount(device));
    }

    /**
     * 查询最近三天未通讯的锁数量
     */
    @PreAuthorize("@ss.hasPermi('lock:device:list')")
    @GetMapping("/noCommuCount")
    public AjaxResult getNoCommuCount(ADevice device)
    {
        return success(aDeviceService.selectNoCommuLockCount(device));
    }

    /**
     * 查询通讯时间异常的锁数量
     */
    @PreAuthorize("@ss.hasPermi('lock:device:list')")
    @GetMapping("/abnormalDateCount")
    public AjaxResult getAbnormalDateCount(ADevice device)
    {
        return success(aDeviceService.selectAbnormalDateLockCount(device));
    }

    /**
     * 获取电量低于指定值的锁数量
     */
    @PreAuthorize("@ss.hasPermi('lock:device:list')")
    @GetMapping("/lowBatteryCount")
    public AjaxResult getLowBatteryCount(ADevice device)
    {
        return success(aDeviceService.selectLowBatteryCount(device));
    }
}
